use nix::unistd::mkdir;
use std::fs::{exists, OpenOptions};
use std::io::Write;
use nix::libc::{pid_t};
use nix::sys::stat::Mode;

pub fn cgroup(memory_use:usize,cpu_use:&str,child_pid:pid_t) -> Result<(), String> {

    println!("cgroup assume v2");
    let mut file = OpenOptions::new()
        .append(true)
        .open("/sys/fs/cgroup/cgroup.subtree_control").map_err(|e| e.to_string())?;
    let _ = file.write_all("+cpu +memory".as_bytes()).map_err(|e| e.to_string())?;
    match exists(format!("/sys/fs/cgroup/my-docker-{child_pid}")).map_err(|e| e.to_string())? {
        true => {}
        false => {
            let _ = mkdir(format!("/sys/fs/cgroup/my-docker-{child_pid}").as_str(),Mode::S_IROTH|Mode::S_IXOTH|Mode::S_IRGRP|Mode::S_IXGRP|Mode::S_IRWXU).map_err(|e|e.to_string())?;
        }
    };

    // let cgroup_files = ["memory.max", "cpu.max"];
    println!("cgroup set memory max");
    let mut memory_max = OpenOptions::new()
        .write(true)
        .truncate(true)
        .open(format!("/sys/fs/cgroup/my-docker-{child_pid}/memory.max")).map_err(|e| e.to_string())?;
    memory_max.write_all(memory_use.to_string().as_bytes()).map_err(|e|e.to_string())?;
    println!("cgroup set cpu max");
    let mut cpu_max = OpenOptions::new()
        .write(true)
        .truncate(true)
        .open(format!("/sys/fs/cgroup/my-docker-{child_pid}/cpu.max")).map_err(|e| e.to_string())?;
    // cpu_max.write_all("50000 100000".as_bytes()).map_err(|e|e.to_string())?;
    cpu_max.write_all(cpu_use.as_bytes()).map_err(|e|e.to_string())?;
    let mut procs_file = OpenOptions::new()
        .append(true)
        .open(format!("/sys/fs/cgroup/my-docker-{child_pid}/cgroup.procs")).map_err(|e| e.to_string())?;
    procs_file.write_all(child_pid.to_string().as_bytes()).map_err(|e|e.to_string())?;
    Ok(())
}
